<?php

/**
 * 
 * 结果输出
 * 
 */

include_once "init.php";


// $files = getfiles(__DIR__."/../sample/1x");

// echo ROOT_PATH;

if(true){
  
  $fields = array(
    '#','样本','阿里','错误','百度','错误','讯飞','错误'
  );

  
  //FILE_APPEND

  function getaliyun($filename){
    $str = file_get_contents(sprintf("%saliyun/%s",RESULT_PATH,$filename));
   
    $json = json_decode($str,true);
    // var_dump($json['result']);
    // return $json['result'];
    // return $json['result'];
    $strings = str_replace("\\r",'',$json['result']);

    return iconv('UTF-8','GB2312',$strings);
  }

  function getbaidu($filename){
    $str = file_get_contents(sprintf("%sbaidu/%s",RESULT_PATH,$filename));
    $json = json_decode($str,true);
    $strings = str_replace("\\r",'',$json['result'][0]);
    return iconv('UTF-8','GB2312',$strings);
  }

  function getxunf($filename){
    $str = file_get_contents(sprintf("%sxunf/%s",RESULT_PATH,$filename));
    $json = json_decode($str,true);

    if(0 != $json['code']){
      return sprintf("err:%d,msg:%s",$json['code'],$json['desc']);
    }
    $strings = str_replace("\\r",'',$json['data']);

    return iconv('UTF-8','GB2312',$strings);
  }

  $files = getm4as(ROOT_PATH.'sample/res');
  $now = date("Ymd");//time();
  $output_name = ROOT_PATH.'out/'.$now.'.csv';
  printf("out:%s".PHP_EOL,$output_name);
  $dir = dirname($output_name);
  if(!is_dir($dir) && !mkdir($dir,true)){
    echo $dir;
    exit();
  }
    
  $fp = fopen($output_name, 'w');
  if(!$fp)
    exit();

  $fieldz = array();

  foreach($fields as $str){
    $fieldz[] = iconv('UTF-8','GB2312',$str);
  }

  fputcsv($fp, $fieldz);

  foreach($files as $file){
    

    
    

    
    $txt = file_get_contents(__DIR__.'/../sample/res/'.$file['filename'].'.txt');
    $lines = preg_split('/\\n/',$txt);

    $len = sizeof($lines);
    for($i = 0 ;$i < $len - 1;$i++){
      // echo substr($lines[$i],6).PHP_EOL;
      $row = array();
      $row[] = iconv('UTF-8','GB2312',sprintf('%s-%d.wav',$file['filename'],$i + 1));
      $row[] = iconv('UTF-8','GB2312',substr($lines[$i],6));
      $filename = sprintf('%s-%d.txt',$file['filename'],$i + 1);
      // $aliyun = getaliyun($filename);
      $row[] = getaliyun($filename);
      $row[] = '';
      $row[] = getbaidu($filename);
      $row[] = '';
      $row[] = getxunf($filename);
      $row[] = '';
      // var_dump($aliyun);
      // $row[] = $aliyun;
      // var_dump(sizeof($row));
      // var_dump($filename);
      fputcsv($fp, $row);
    }
    

    

    // $strings = file_get_contents($output_name);
    // // $strings = io

    // if("10" != $file['filename']){
    //   // printf("time:%d",time());
    //   // continue;
    //   file_put_contents($output_name,iconv('UTF-8','GB2312',$strings));
    // }
    
  }
  
  fclose($fp);
}



?>